<script>
import setImage from '@/assets/images/user.png'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import UserInfo from '@/portal4.1/components/solt/user.vue'
import { layout } from '@/mixins/layout'
import { requestGet } from '@/api/system/common'
import { saveSearchHistory, getSearchHistory, delSearchHistory } from '@/api/service/index'

export default {
  name: 'DefaultQueryHeader',
  components: { UserInfo },
  mixins: [layout],
  data() {
    return {
      dataList: [],
      userShow: false,
      userImage: setImage,
      fixed: false,
      title: '',
      entity: { userid: '', searchContent: '', searchDate: '' },
      searchDataList: [],
      historyDataList: [],
      search: [], // 记录历史查询记录
      value: false
    }
  },
  computed: {
    user() {
      return this.$store.getters.user
    },
    DefaultBackground() {
      return { background: 'url(' + this.layoutTheme.headerBackGroundImage + ') no-repeat', backgroundSize: '100% 100%' }
    },
    ...mapGetters(
      ['layout', 'menuId', 'user']
    ),
    customHeaderFlex() {
      if (this.fixed) {
        return { backgroundColor: this.layoutTheme.headerBarBackground }
      } else {
        return {}
      }
    },
    customHeaderLi() {
      return { '--font-color': this.layoutTheme.headerBarTabColor, '--before-destroy': this.layoutTheme.headerBarTabColor }
    },
    customHeaderQueryBody() {
      return { '--back-color': this.layoutTheme.headerQueryBackground }
    },
    customHeaderQueryButton() {
      return { '--query-button-bak': this.layoutTheme.headerQueryButtonBackground, '--query-button-color': this.layoutTheme.headerQueryButtonColor }
    },
    customHeaderQueryAssets() {
      return { '--query-assets': this.layoutTheme.headerQueryAssistColor }
    }
  },
  watch: {
    layout(data) {
      this.initMenu(data.id)
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.initMenu(this.layout.id)
    if (this.$route.query.title) {
      this.title = this.$route.query.title
    }
    this.getSearchHis()
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    initMenu(data) {
      if (undefined === data || data === null) {
        data = 0
      }
      if (getToken()) {
        // 查询布局下面的菜单信息
        requestGet('rest/api/layout/v1/menu/pc/query/menus/layout', { lid: data }).then(res => {
          const { data } = res
          // 菜单数据
          this.dataList = data.reverse()
        })
      } else {
        requestGet('rest/api/guest/layout/v1/menu/pc/query/menus/layout', { lid: data }).then(res => {
          const { data } = res
          this.dataList = data.reverse()
        })
      }
    },
    // 设置当前激活的菜单
    setActiveId(data) {
      this.$router.push({ path: '/uc/index', query: { lid: data }})
    },
    setActive(data) {
      this.title = data
      this.value = false
    },
    openInfo() {
      this.userShow = true
      this.$nextTick(() => {
        this.$refs.user.triggerOnClick()
      })
    },
    closeInfo() {
      this.userShow = false
      this.$nextTick(() => {
        this.$refs.user.triggerOnClick()
      })
    },
    userInfo(data) {
      this.userShow = data
    },
    handleScroll() {
      this.$nextTick(() => {
        if (this.$refs.header !== undefined) {
          this.offsetTop = this.$refs.header.offsetTop
          const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
          this.fixed = scrollTop > 60
        }
      })
    },
    // 查询前十条历史记录
    getSearchHis() {
      (async() => {
        try {
          const resList = await getSearchHistory({ page: 1, size: 10 })
          if (resList.code === 200) {
            this.searchDataList = resList.data.data
            this.search = []
            this.historyDataList = this.searchDataList
            if (resList.data.pagerSize > 3) {
              this.historyDataList = this.historyDataList.slice(0, 3)
            }
            if (this.historyDataList.length > 0) {
              this.historyDataList.forEach(item => {
                this.search.push(item.searchContent)
              })
            }
          }
        } catch (error) {
          this.$message({
            message: '查询失败！',
            type: 'warning',
            customClass: 'messageIndex'
          })
        }
      })()
    },
    // 保存查询记录
    saveHistory(data) {
      (async() => {
        try {
          const result = await saveSearchHistory(data)
          if (result.code === 200) {
            this.getSearchHis()
            this.$message({
              message: '保存成功',
              type: 'success',
              customClass: 'messageIndex'
            })
          }
        } catch (error) {
          this.$message({
            message: '保存失败！',
            type: 'warning',
            customClass: 'messageIndex'
          })
        }
      })()
    },
    deleteHis() {
      (async() => {
        try {
          const userid = this.$store.getters.user.username
          const result = await delSearchHistory(userid)
          if (result.code === 200) {
            this.getSearchHis()
            this.$message({
              message: '删除成功',
              type: 'success',
              customClass: 'messageIndex'
            })
          }
        } catch (error) {
          this.$message({
            message: '删除失败！',
            type: 'warning',
            customClass: 'messageIndex'
          })
        }
      })()
    },
    query() {
      this.value = false
      // this.$emit('queryObject', this.title)
      const userid = this.$store.getters.user.username
      this.entity.searchDate = new Date().getTime()
      this.entity.userid = userid
      this.entity.searchContent = this.title
      if (this.title != null && this.title) {
        this.title.filter
        const length = this.searchDataList.length
        const a = this.searchDataList.filter(item => {
          return item.searchContent.toLowerCase() !== this.title.toLowerCase()
        }).length
        if (length === a) {
          this.saveHistory(this.entity)
        }
        this.queryServer(this.title)
      }
    }
  }
}
</script>

<template>
  <div class="layout-main" :style="DefaultBackground">
    <div class="portal-layout-header">
      <div ref="header" class="layout-header-logo">
        <div :class="fixed === false? 'custom-header': 'custom-header-flex'" :style="customHeaderFlex">
          <div class="custom-menu">
            <el-image :src="layoutTheme.headerLogo" />
            <div
              v-for="(data,index) in dataList"
              :key="'menu-'+index"
              class="custom-lu-li"
              :style="customHeaderLi"
              :class="menuId === data.id ? 'active': ''"
              @click="setActiveId(data.id)"
            ><i v-if="data.sfsxtb" :class="data.tb" />
              {{ data.name }}</div>
          </div>
          <div class="nav-bar">
            <user-info ref="user" :trigger="'hover'" @callBack="userInfo">
              <div
                slot="user"
                class="header-info"
                @mouseenter="openInfo"
                @mouseleave="closeInfo"
              >
                <div class="user-image">
                  <el-image :src="(user.avatarName === null||user.avatarName === undefined) ? userImage: user.avatarName">
                    <div slot="error" class="image-slot">
                      <el-image :src="userImage" />
                    </div>
                  </el-image>
                </div>
                <div class="user-info" :style="{ color: layoutTheme.headerBarTabColor}">{{ user.nickName }}</div>
                <div class="user-icon" :style="{ color: layoutTheme.headerBarTabColor}">
                  <i v-if="userShow === false" class="el-icon-arrow-down" />
                  <i v-else class="el-icon-arrow-up" />
                </div>
              </div>
            </user-info>
          </div>
        </div>
        <div class="portal-search">
          <div class="search-body">
            <el-popover v-model="value" placement="bottom" trigger="focus" :width="630">
              <template #reference>
                <div class="search-custom-input" :style="customHeaderQueryBody">
                  <div class="input-body">
                    <input v-model="title" class="custom-input" placeholder="请输入要查询的内容">
                  </div>
                  <div class="input-button" :style="customHeaderQueryButton" @click="query">查询</div>
                </div>
              </template>
              <template #default>
                <div class="search-old-header" :style="customHeaderQueryAssets">
                  <span class="lableText">历史搜索</span>
                  <span class="lableButton" @click="deleteHis"><i :style="customHeaderQueryAssets" class="el-icon-delete" /></span>
                </div>
                <div
                  v-for="item in searchDataList"
                  :key="item.id"
                  class="search-old-li"
                  :style="customHeaderQueryAssets"
                  @click="setActive(item.searchContent)"
                >
                  {{ item.searchContent }}

                </div>
              </template>
            </el-popover>
            <div style="color: #fff">历史搜索：<span
              v-if="search"
              class="search-custom-old"
              :style="customHeaderQueryAssets"
            >
              {{ search.join(',') }}
            </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.layout-main {
  width: 100%;
  height: 100%;
}
.portal-layout-header {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}
.layout-header-logo {
  height: 60px;
  width: 100%;
  box-shadow: 0 0 8px #00000014;
}
.custom-header {
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
}
.custom-header-flex {
  left: 0;
  top: 0;
  height: 60px;
  right: 0;
  position: fixed;
  z-index: 100000;
  box-shadow: 0 0 8px #00000014;
}
.custom-header,.custom-header-flex {
  line-height: 60px;
  min-width: 75rem;
  padding: 0 calc(50% - 40.8rem);
  display: flex;
  justify-content: space-between;
  align-items: center;
  .custom-menu {
    height: 60px;
    line-height: 60px;
    display: flex;
    .el-image {
      height: 40px;
      margin-top: 10px;
    }
    .custom-lu-li {
      font-size: 1.1rem;
      padding: 0 10px;
      box-sizing: border-box;
      cursor: pointer;
      color: var(--font-color);
    }
    .custom-lu-li:not(:first-child) {
      margin-left: 5px;
    }
    .custom-lu-li.active,
    .custom-lu-li:hover {
      font-weight: bolder;
      border-bottom: 2px solid var(--before-destroy);
    }
  }
}
.header-info {
  height: 60px;
  line-height: 60px;
  width: 120px;
  display: flex;
  flex-flow: row nowrap;
  cursor: pointer;
  .user-image {
    flex: 0 1 auto;
    width: 36px;
    height: 46px;
    padding: 10px 5px;
    box-sizing: border-box;
    .el-image {
      width: 100%;
      height: 100%;
    }
  }
  .user-info {
    flex: 0 1 auto;
    width: 70px;
    height: 100%;
    line-height: 40px;
  }
}
.portal-search {
  width: 100%;
  height: 80px;
  min-width: 75rem;
  padding: 0 calc(50% - 46.5rem);
  position: relative;
  box-sizing: border-box;
  margin-top: 150px;
  .search-body {
    margin: 0 auto;
    width: 630px;
    height: 80px;
    .search-custom-input {
      width: 100%;
      height: 48px;
      border-radius: 2px;
      border: none;
      background-color: var(--back-color);
      display: flex;
      .input-body {
        width: 540px;
        height: 48px;
        line-height: 40px;
        padding: 4px 20px;
        box-sizing: border-box;
        .custom-input {
          display: block;
          border: none;
          width: 100%;
          height: 40px;
        }
      }
      .input-button {
        width: 90px;
        text-align: center;
        line-height: 48px;
        height: 48px;
        background-color: var(--query-button-bak);
        border-radius: 0 2px 2px 0;
        letter-spacing: 5px;
        font-size: 1.1rem;
        color: var(--query-button-color);
      }
    }
    .search-old-header {
      // width: 100%;
      width: 500px;
      height: 20px;
      font-size: 0.9rem;
      line-height: 20px;
      display: flex;
      justify-content: space-between;
      color: var(--query-assets);
      .lableText{
        width: 200px;
        flex: 0 1 auto;
      }
      .lableButton{
        width: 50px;
      }
    }

    .search-old-li {
      width: 100%;
      height: 30px;
      line-height: 30px;
    }

    .search-custom-old {
      width: 100%;
      height: 32px;
      line-height: 38px;
      overflow: hidden;
      text-align: left;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: var(--query-assets);
    }
  }
}

input:focus {
  outline: none;
}
</style>
